package com.kakavr.wxpay.service;

import java.math.BigDecimal;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.kakavr.base.service.BaseService;
import com.kakavr.pay.constant.WxConstant;
import com.kakavr.pay.util.HttpClientUtil;
import com.kakavr.pay.util.WXPayUtil;
import com.kakavr.wxpay.dao.IWXTransferDao;

@Service
public class WXTransferService extends BaseService implements
		IWXTransferService {
	@Resource
	private IWXTransferDao wXTransferDao;

	@Override
	public int addSplitPayLog(Object storeId, Object openid,Object splitId, BigDecimal money) {
		int returnInt = 2;
		Map<String, String> orderMap = Maps.newHashMap();
		orderMap.put("mch_appid", WxConstant.getAppId());
		orderMap.put("mchid", WxConstant.getMchId());
		orderMap.put("nonce_str", WXPayUtil.generateUUID());
		orderMap.put("partner_trade_no",
				String.valueOf(WXPayUtil.getCurrentTimestampMs()));
		orderMap.put("openid", (String)openid);
		orderMap.put("check_name", "NO_CHECK");
		orderMap.put("amount", money.multiply(new BigDecimal("100")).intValue()+"");
//		orderMap.put("amount", "100");
		orderMap.put("desc", "卡卡VR分账");
		orderMap.put("spbill_create_ip", "114.114.114.114");
		try {
			String xml = WXPayUtil.generateSignedXml(orderMap,
					WxConstant.getAppKey());
			Map<String, String> result = HttpClientUtil
					.doSSLPostByXML(
							"https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers",
							xml, WxConstant.getMchId());
			orderMap.putAll(result);
			if("SUCCESS".equals(result.get("result_code"))){
				returnInt = 1;
			}
		} catch (Exception e) {
			error("微信分账出错，错误信息："+e);
		}
		orderMap.put("status", String.valueOf(returnInt));
		orderMap.put("storeId", storeId.toString());
		orderMap.put("splitId", String.valueOf(splitId));
		wXTransferDao.insertSplitWxpayLog(orderMap);
		return returnInt;
	}
}
